package com.weishi.project.speedometer.controller;

import com.weishi.common.utils.DateUtils;
import com.weishi.common.utils.GPSUtil;
import com.weishi.common.utils.StringUtils;
import com.weishi.framework.redis.RedisCache;
import com.weishi.framework.web.controller.BaseController;
import com.weishi.framework.web.domain.AjaxResult;
import com.weishi.project.speedometer.service.IMantianxingService;
import com.weishi.project.speedometer.service.ISpeedometerService;
import com.weishi.project.speedometer.service.IWitService;
import com.weishi.project.speedometer.vo.MantianxingGpsVo;
import com.weishi.project.speedometer.vo.PropellerFrequencyData;
import com.weishi.project.training.domain.ShipSpeedRecord;
import com.weishi.project.training.domain.ShipSpeedRecordLog;
import com.weishi.project.training.domain.TrainingGroupChannel;
import com.weishi.project.training.domain.WitAccLog;
import com.weishi.project.training.service.*;
import com.weishi.tcp.tcpserver.TCPServer;
import com.weishi.tcp.vo.TcpMassageDataVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.logging.Logger;

@RestController
@RequestMapping("/shipSpeed/")
@CrossOrigin("*")//解决移动端跨域
@Api(value = "speedometer", description = "船速仪")
public class ApiController extends BaseController {

    @Autowired
    private IShipSpeedService shipSpeedService;


    @Autowired
    private IShipSpeedRecordService shipSpeedRecordService;

    @Autowired
    private IShipSpeedRecordLogService shipSpeedRecordLogService;

    @Autowired
    private IAccelerationLogService accelerationLogService;

    @Autowired
    private ISpeedometerService speedometerService;

    @Autowired
    private IMantianxingService mantianxingService;

    @Autowired
    private ITrainingGroupChannelService trainingGroupChannelService;

    @Autowired
    private IWitService witService;

    @Autowired
    private RedisCache redisCache;

    Logger logger = Logger.getLogger("speedometer");

    @ApiOperation("根据船速仪 id 查询船速仪实时数据")
    @GetMapping("/getShipSpeed")
    public AjaxResult getShipSpeed(String channelId) {
        int channel_id = Integer.parseInt(channelId);
        return AjaxResult.success(shipSpeedRecordLogService.selectDataListByChannelId(channel_id));
    }

    @ApiOperation("查询历史数据")
    @GetMapping("/queryShipSpeed")
    public AjaxResult queryShipSpeed(ShipSpeedRecord shipSpeedRecord) {
        List<ShipSpeedRecord> list = shipSpeedRecordService.selectShipSpeedRecordList(shipSpeedRecord);
        return AjaxResult.success(list);
    }

    @ApiOperation("查询船速仪状态")
    @GetMapping("/getShipSpeedStatus")
    public AjaxResult getShipSpeedStatus(String shipSpeedNo) {

        return AjaxResult.success(shipSpeedService.getShipSpeedStatus(shipSpeedNo));
    }

    @ApiOperation("查询船速仪实时速度")
    @GetMapping("/qryCurrentSpeed")
    public AjaxResult qryCurrentSpeed(String shipSpeedNo, Integer channelId) {
        return AjaxResult.success(shipSpeedRecordLogService.qryCurrentSpeed(shipSpeedNo));
    }

    @ApiOperation("查询实时桨频")
    @GetMapping("/qryCurrentPropellerFrequency")
    public AjaxResult qryCurrentPropellerFrequency(String shipSpeedNo, Integer channelId) {
        return AjaxResult.success(accelerationLogService.qryCurrentPropellerFrequency(shipSpeedNo, channelId));
    }

    @ApiOperation("查询桨频原始数据")
    @GetMapping("/qryAccelerationLog")
    public AjaxResult qryAccelerationLog(Integer channelId) {
        return AjaxResult.success(accelerationLogService.qryAccelerationLogList(channelId));
    }

    /**
     * 船速仪数据上传（ps:当socket断开连接时调用http接口上传数据）
     *
     * @return
     */
    @ApiOperation("船速仪数据上传")
    @PostMapping("/addRealTimeData")
    public AjaxResult addRealTimeData(@RequestBody List<TcpMassageDataVo> massageDates) {
        speedometerService.addRealTimeData(massageDates);
        return AjaxResult.success();
    }

    @ApiOperation(value = "踢掉指定设备的长连接")
    @GetMapping("/killTcp")
    public AjaxResult killTcp(@RequestParam Map<String, Object> objectMap) {
        TCPServer tcpServer = TCPServer.getInstance();
        tcpServer.destroyAllClient();
        return AjaxResult.success();
    }

    @ApiOperation(value = "满天星云高精度gps数据")
    @RequestMapping(method = RequestMethod.POST, value = "/postGps")
    @ResponseBody
    public AjaxResult postGps(HttpServletRequest request) {
        try {
            InputStream inputStream = request.getInputStream();
            StringBuffer aa = new StringBuffer();
            byte[] i = new byte[5];
            int index = inputStream.read(i);
            while (index > 0) {
                aa.append(new String(i));
                index = inputStream.read(i);
            }
            MantianxingGpsVo vo = MantianxingGpsVo.changeVo(aa.toString());
            mantianxingService.addTempList(vo);
            logger.info(vo.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return AjaxResult.success();
    }

    //过期
    @ApiOperation(value = "满天星云高精度gps数据")
    @RequestMapping(method = RequestMethod.GET, value = "/getGpsList1")
    @ResponseBody
    public AjaxResult getGpsList1(HttpServletRequest request) {
        String deviceId = request.getParameter("deviceId");
        List<MantianxingGpsVo> list = mantianxingService.getList(deviceId);
        Map<String, Object> ret = new HashMap<>();
        List<String> x = new ArrayList<>();
        List<Double> ySpeed = new ArrayList<>();
        List<Double> ySpeedToDistance = new ArrayList<>();
        List<Double> yDistanceTotal = new ArrayList<>();
        List<Double> yDistance = new ArrayList<>();

        for (MantianxingGpsVo vo : list) {
            x.add(vo.getLocalTime());
            ySpeed.add(vo.getSpeed());
            ySpeedToDistance.add(vo.getSpeedTodistance());
            yDistanceTotal.add(vo.getDistanceTotal());
            yDistance.add(vo.getDistance());
        }

        ret.put("x", x);
        ret.put("ySpeed", ySpeed);
        ret.put("ySpeedToDistance", ySpeedToDistance);
        ret.put("yDistanceTotal", yDistanceTotal);
        ret.put("yDistance", yDistance);

        if(list.size()>0){
            MantianxingGpsVo last = list.get(list.size()-1);
            Map<String, Object> info = new HashMap<>();
            info.put("xrms",last.getXrms());
            info.put("yrms",last.getYrms());
            info.put("hrms",last.getHrms());
            info.put("quality",last.getQuality());
            info.put("solutionUsedSats",last.getSolutionUsedSats());
            ret.put("info",info);

            //桨频数据
            List<PropellerFrequencyData> propellerFrequencyDatas = mantianxingService.getPropellerFrequencyData(list,2);
            Map<String, Object> propellerFrequencyMap = new HashMap<>();
            List<String> xp = new ArrayList<>();
            List<Long> yp = new ArrayList<>();
            for(PropellerFrequencyData propellerFrequencyData : propellerFrequencyDatas){
                xp.add(propellerFrequencyData.getRealTime());
                yp.add(Math.round(propellerFrequencyData.getAveragePropeller()));
            }
            propellerFrequencyMap.put("xpropellerFrequency",xp);
            propellerFrequencyMap.put("ypropellerFrequency",yp);
            ret.put("propellerFrequency",propellerFrequencyMap);
        }

        return AjaxResult.success(ret);
    }

    @ApiOperation(value = "满天星云高精度gps数据")
    @RequestMapping(method = RequestMethod.GET, value = "/getGpsList")
    @ResponseBody
    public AjaxResult getGpsList(HttpServletRequest request) {
        Map<String, Object> ret = new HashMap<>();

        String channelId = request.getParameter("channelId");
        TrainingGroupChannel trainingGroupChannel = trainingGroupChannelService.getById(Integer.parseInt(channelId));
        ShipSpeedRecordLog params = new ShipSpeedRecordLog();
        params.setChannelId(trainingGroupChannel.getId());
        List<ShipSpeedRecordLog> list = shipSpeedRecordLogService.selectShipSpeedRecordLogList(params);
        if(StringUtils.isNotEmpty(list)) {
            ret.put("realData", getTableData(list, trainingGroupChannel.getStime()));

            //桨频数据
            List<PropellerFrequencyData> propellerFrequencyDatas = mantianxingService.getPropellerFrequencyData(list);
            Map<String, Object> propellerFrequencyMap = new HashMap<>();
            List<String> xp = new ArrayList<>();
            List<Long> yp = new ArrayList<>();
            List<Double> yd = new ArrayList<>();
            for(PropellerFrequencyData propellerFrequencyData : propellerFrequencyDatas){
                xp.add(propellerFrequencyData.getRealTime());
                yp.add(Math.round(propellerFrequencyData.getAveragePropeller()));
                yd.add(propellerFrequencyData.getDistance());
            }
            propellerFrequencyMap.put("xpropellerFrequency",xp);
            propellerFrequencyMap.put("ypropellerFrequency",yp);
            propellerFrequencyMap.put("yDistance",propellerFrequencyDatas.size());
            ret.put("propellerFrequency",propellerFrequencyMap);

        }

        return AjaxResult.success(ret);
    }

    @ApiOperation(value = "清空满天星云高精度gps数据")
    @RequestMapping(method = RequestMethod.GET, value = "/clearGpsList")
    @ResponseBody
    public AjaxResult clearGpsList(HttpServletRequest request) {
        String deviceId = request.getParameter("deviceId");
        mantianxingService.clearTempList(deviceId);
        return AjaxResult.success();
    }

    private Map<String, Object> getTableData(List<ShipSpeedRecordLog> list, Date startTime) {
        Map<String, Object> ret = new HashMap<>();
        List<String> x = new ArrayList<>();
        List<Double> ySpeed = new ArrayList<>();
        List<Double> yDistanceTotal = new ArrayList<>();
        List<Double> yDistance = new ArrayList<>();
        ShipSpeedRecordLog pre = list.get(0);
        double distanceTotal = 0.0;
        for (ShipSpeedRecordLog shipSpeedRecordLog : list) {
            double clearance = GPSUtil.GetDistance1(pre.getLatitude(),pre.getLongitude(),shipSpeedRecordLog.getLatitude(),shipSpeedRecordLog.getLongitude());
            distanceTotal += clearance;
            x.add(getRealTime(startTime,Long.parseLong(shipSpeedRecordLog.getTimp())));
            ySpeed.add(shipSpeedRecordLog.getSpeed());
            yDistanceTotal.add(distanceTotal);
            yDistance.add(shipSpeedRecordLog.getDistance());
            pre = shipSpeedRecordLog;
        }

        ret.put("x", x);
        ret.put("ySpeed", ySpeed);
        ret.put("yDistanceTotal", yDistanceTotal);
        ret.put("yDistance", yDistance);
        return ret;
    }

    private String getRealTime(Date startTime, long end) {
        long start = startTime.getTime();
        return DateUtils.getStringTime(end - start);

    }

    /************************************* 9轴传感器 *******************************************/
    @ApiOperation(value = "桨频数据")
    @RequestMapping(method = RequestMethod.GET, value = "/getPropellerFrequencyList")
    @ResponseBody
    public AjaxResult getPropellerFrequencyList(HttpServletRequest request) {
        Map<String, Object> ret = new HashMap<>();

        String devId = request.getParameter("deviceId");
        List<WitAccLog> list = witService.getList(devId);
        if(list==null || list.size()==0){
            return AjaxResult.success();
        }
        long fisrtTime = Long.parseLong(list.get(0).getTimp());
        if(StringUtils.isNotEmpty(list)) {
            Map<String, Object> witDatas = new HashMap<>();
            List<String> x = new ArrayList<>();
            List<Double> ySpeed = new ArrayList<>();
            List<Double> yDistanceTotal = new ArrayList<>();
            List<Double> yDistance = new ArrayList<>();
            for(WitAccLog witDataVo : list){
                x.add(DateUtils.getStringTime(Long.parseLong(witDataVo.getTimp())-fisrtTime));
                ySpeed.add(witDataVo.getAnglex());
                yDistanceTotal.add(witDataVo.getAngley());
                yDistance.add(witDataVo.getAnglez());
               /* yDistanceTotal.add((double)witDataVo.getNode());
                yDistance.add(witDataVo.getWx());*/
            }
            witDatas.put("x", x);
            witDatas.put("ySpeed", ySpeed);
            witDatas.put("yDistanceTotal", yDistanceTotal);
            witDatas.put("yDistance", yDistance);

            ret.put("realData", witDatas);

            //桨频数据
            List<PropellerFrequencyData> propellerFrequencyDatas = witService.getPropellerFrequencyData(list,4);
            Map<String, Object> propellerFrequencyMap = new HashMap<>();
            List<String> xp = new ArrayList<>();
            List<Long> yp = new ArrayList<>();
            List<Double> yd = new ArrayList<>();
            for(PropellerFrequencyData propellerFrequencyData : propellerFrequencyDatas){
                long time = Long.parseLong(propellerFrequencyData.getRealTime());
                xp.add(DateUtils.getStringTime(time-fisrtTime));
                yp.add(Math.round(propellerFrequencyData.getAveragePropeller()));
                yd.add((double)propellerFrequencyDatas.size());
            }
            propellerFrequencyMap.put("xpropellerFrequency",xp);
            propellerFrequencyMap.put("ypropellerFrequency",yp);
            propellerFrequencyMap.put("yDistance",yd);
            ret.put("propellerFrequency",propellerFrequencyMap);

            ret.put("info",propellerFrequencyDatas.size());

        }

        return AjaxResult.success(ret);
    }

    @ApiOperation(value = "清空传感器缓存数据")
    @RequestMapping(method = RequestMethod.GET, value = "/clearMitList")
    @ResponseBody
    public AjaxResult clearMitList(HttpServletRequest request) {
        String deviceId = request.getParameter("deviceId");
        witService.clearTempList(deviceId);
        return AjaxResult.success();
    }

}
